package com.inno.subject.domain.strategy.ai;

import com.inno.subject.domain.entity.InterviewBO;
import com.inno.subject.domain.utils.ApplicationContextUtil;
import com.inno.subject.domain.utils.ChatClientUtil;
import com.inno.subject.domain.websocket.SubjectSocket;
import jakarta.websocket.Session;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author sean
 */
public interface InterviewMockHandler {

    String getType();

    void handle(InterviewBO interviewBO);


    /**
     * 开始对话
     */
    default void start(InterviewBO interviewBO ,String quotation,ChatClientUtil chatClientUtil, String systemMessage){
        String message = interviewBO.getMessage();
        SubjectSocket socket = ApplicationContextUtil.getWebSocket();
        Long currentUser = interviewBO.getCurrentUser();
        Session session = socket.getSession(currentUser);
        if (Objects.isNull(session) || !session.isOpen()){
            return;
        }
        // 引语
        if (StringUtils.isBlank(interviewBO.getMessage())) {
            socket.sendMessage(session, quotation);
            return;
        }

        List<String> finalList = new CopyOnWriteArrayList<>();
        chatClientUtil.streamingCall(message, systemMessage, currentUser).subscribe(
                response -> ChatClientUtil.processorSubscribe(response, finalList, socket, session),
                error -> socket.sendMessage(session, "服务器开小差了...，请稍后重试"),
                () -> {
                    String finalMessage = finalList.get(finalList.size() - 1);
                    chatClientUtil.addHistoryMessage(finalMessage, currentUser);

                }
        );
    }
}
